<?php
/**
 *	@func Mongo 缓存(百度云版)
 *	@author midoks
 *	@link midoks.cachecha.com
 */
class BaeMongoCache{
	public $cfg = array();

	public $client;//客服端
	public $link;//连接资源
	public $collection;//文档型资源

	//架构函数
	public function __construct(){
		$this->cfg = array(
			'host' => getenv('HTTP_BAE_ENV_ADDR_MONGO_IP'),
			'port' => getenv('HTTP_BAE_ENV_ADDR_MONGO_PORT'),
			'user' => getenv('HTTP_BAE_ENV_AK'),
			'pwd'  => getenv('HTTP_BAE_ENV_SK'),
			//数据库名字
			'dbname'=> 'pkVuHXvBUPciyCBCTTwh',
		);

		//try {
		//连接资源
		$this->client = new MongoClient("mongodb://{$this->cfg['host']}:{$this->cfg['port']}");
		//选择数据库
		$this->link = $this->client->selectDB($this->cfg['dbname']);
		//用户认证
		$this->link->authenticate($this->cfg['user'], $this->cfg['pwd']);

		//接下来接可以对该库上的集群进行操作了,具体操作方法请参考PHP_mongodb官方文档
		$this->collection = $this->link->selectCollection('wpdbcache');

		//var_dump($this);
		//} catch (Exception $e){
		//	die($e->getMessage());
		//}
	}

	//析构函数
	public function __destruct(){
		$this->link->close();
	}


	/**
	 *	@func 向MongoDB服务器中,写入值
	 *	@param $key key值
	 *	@param $value value值
	 *	@return 返回
	 */
	public function write($key, $value){

		//var_dump($key, $value);
		//return;
		
		//查找是否存在
		$data = $this->collection->findOne(array('id'=>$key));
		//加入添加时间
		$value = array_merge($value, array('time_insert_to_mongodb'=>time()));
		//var_dump($value);
		$value = base64_encode(serialize($value));
		//var_dump($data);
		$bool = false;
		if(!$data){
			$bool = $this->collection->insert(array('id'=>$key, 'value'=>$value));
			//var_dump($bool);
		}else{//存在,就更新操作
			$bool = $this->collection->update(array('id'=>$key), array('$set'=>array('value'=>$value)));
			//var_dump($bool);
		}

		
	}

	/**
	 *	@func 向Mongo服务获取值
	 *	@param $key key值
	 */
	public function read($key){
		//return false;
		$data = $this->collection->findOne(array('id'=>$key));
		//$num = $this->collection->count();//总数
		if(!empty($data['value'])){
			//var_dump(unserialize(base64_decode($data['value'])));
			$data = unserialize(base64_decode($data['value']));
			if(($data['time_insert_to_mongodb'] + $this->cfg['timeout']) > time()){
				//var_dump($data);
				return $data;
			}else{
				return false;
			}
		}
		return false;
	}

	/**
	 *	@func 在Mongo服务器中删除一个元素
	 */
	public function delete($key){
		$this->link->remove(array($key));
	}

	/**
	 *	@func 清空Mongo中的所有数据
	 */
	public function flush(){
		$this->link->remove();
	}

	//清空过期数据
	public function flush_expire(){
		//会自动销毁
	}
}
?>
